<template>
  <div>
    <a-form
      :model="communityInfo"
      name="basic"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 12 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="社区名称"
        name="communityName"
        :rules="[{ required: true, message: '请输入的社区名称！' }]"
      >
        <a-input v-model:value="communityInfo.communityName" />
      </a-form-item>

      <a-form-item name="communityImage" label="社区图片">
        <Upload
          v-model="imagePath"
          action="http://localhost:8099/common/uploadOss"
          @submitImg="submitImg"
        />
      </a-form-item>

      <a-form-item
        label="省市区"
        name="districtsId"
        :rules="[{ required: true, message: '请输入的社区名称！' }]"
      >
        <a-cascader
          v-model:value="positionVal"
          :options="options"
          :load-data="loadData"
          placeholder="请选择省市区"
          change-on-select
          @change="changePosition"
          :allowClear="false"
        />
      </a-form-item>

      <a-form-item
        label="社区地址"
        name="communityAddress"
        :rules="[{ required: true, message: '请输入的社区地址！' }]"
      >
        <a-input
          placeholder="请输入的社区地址"
          v-model:value="communityInfo.communityAddress"
        />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button style="margin-right: 20px" type="primary" html-type="submit"
          >提交</a-button
        >
        <a-button @click="reset">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue'
import { deleteImage } from '@/api/config/api'
import { apiAdd, apiGetDetails, apiUpdate } from '@/api/Community/api'
import { onMounted, ref } from 'vue'
import { getCity } from '@/api/Community/api'
import { CommunityModel } from '@/api/Community/model'
import Upload from '@/common/Upload.vue'

const props = defineProps(['communityId'])
const emit = defineEmits(['receiveData'])
const positionVal = ref<any>([])
const communityInfo: any = ref<CommunityModel>({
  communityId: null,
  communityName: '',
  communityImage: '',
  provincesId: null,
  citiesId: null,
  districtsId: null,
  communityAddress: '',
  provincesName: '',
  citiesName: '',
  districtsName: '',
})

const imagePath = ref('')
//省市区数据
const options = ref([])
const imageUrl = ref<any>('')
const level = ref(0)
const submitImg = (url: any) => {
  let data: any = url
  communityInfo.value.communityImage = data.value.data
}
//提交数据
const onFinish = async () => {
  let { communityId } = communityInfo.value

  if (communityId == null) {
    try {
      await apiAdd(communityInfo.value)
      Object.keys(communityInfo.value).forEach(
        (key) => delete communityInfo.value[key]
      )
      emit('receiveData', 3)
    } catch (error) {
      emit('receiveData', 4, error)
    }
  } else {
    try {
      await apiUpdate(communityInfo.value)
      Object.keys(communityInfo.value).forEach(
        (key) => delete communityInfo.value[key]
      )
      emit('receiveData', 1)
    } catch (error) {
      emit('receiveData', 2, error)
    }
  }
}

const changePosition = (val: any, selectedOptions: any) => {
  communityInfo.value.communityAddress = ''
  communityInfo.value.provincesId = val[0]
  communityInfo.value.citiesId = val[1]
  communityInfo.value.districtsId = val[2]
  communityInfo.value.provincesName = selectedOptions[0]
    ? selectedOptions[0].label
    : ''
  communityInfo.value.citiesName = selectedOptions[1]
    ? selectedOptions[1].label
    : ''
  communityInfo.value.districtsName = selectedOptions[2]
    ? selectedOptions[2].label
    : ''

  if (selectedOptions.length == 3) {
    let { provincesName, citiesName, districtsName } = communityInfo.value
    communityInfo.value.communityAddress =
      provincesName + citiesName + districtsName
  }
}

//数据加载
const loadData = (selectedOptions: any) => {
  const targetOption = selectedOptions[selectedOptions.length - 1]
  targetOption.loading = true
  setTimeout(async () => {
    if (
      communityInfo.value.provincesId &&
      communityInfo.value.citiesId == null
    ) {
      targetOption.loading = false
      level.value = 1
      // parentCode1.value = targetOption.value
      let res = await getCity({
        parentCode: targetOption.value,
        level: 1,
      })
      targetOption.children = res.data.map((item: any) => {
        return {
          value: item.areaCode,
          label: item.name,
          isLeaf: false,
        }
      })
    } else if (
      communityInfo.value.citiesId &&
      communityInfo.value.districtsId == null
    ) {
      targetOption.loading = false
      level.value = 2

      let res = await getCity({
        parentCode: communityInfo.value.citiesId,
        level: 2,
      })
      targetOption.children = res.data.map((item: any) => {
        return {
          value: item.areaCode,
          label: item.name,
        }
      })
    }
    options.value = [...options.value]
  }, 100)
}

const onFinishFailed = () => {
  console.log('提交失败！')
}

//修改时获取省市区的初始数据
const initPositionData = async (
  provincesId: any,
  citiesId: any,
  districtsId: any
) => {
  positionVal.value = [provincesId, citiesId, districtsId]
  // 初始化获取省级
  let provinces = await getCity({
    parentCode: 0,
    level: 0,
  })
  options.value = provinces.data.map((item: any) => {
    return {
      value: item.areaCode,
      label: item.name,
      isLeaf: false,
    }
  })
  // 初始化获取城市级
  let cities = await getCity({
    parentCode: provincesId,
    level: 1,
  })

  let citieChildren = cities.data.map((item: any) => {
    return {
      value: item.areaCode,
      label: item.name,
      isLeaf: false,
    }
  })

  //初始化县级
  let districts = await getCity({
    parentCode: citiesId,
    level: 2,
  })
  let districtChildren = districts.data.map((item: any) => {
    return {
      value: item.areaCode,
      label: item.name,
    }
  })

  options.value.forEach((ele: any) => {
    if (ele.value == provincesId) {
      ele.children = citieChildren
      ele.children.forEach((item: any) => {
        if (item.value == citiesId) {
          item.children = districtChildren
        }
      })
    }
  })
}
//重置表单数据
const reset = async () => {
  Object.keys(communityInfo.value).forEach(
    (key) => delete communityInfo.value[key]
  )
}

onMounted(async () => {
  if (props.communityId != null) {
    let res = await apiGetDetails(props.communityId)
    communityInfo.value = res.data
    imagePath.value = communityInfo.value.communityImage
    //修改时获取数据原来的省市区
    initPositionData(
      communityInfo.value.provincesId,
      communityInfo.value.citiesId,
      communityInfo.value.districtsId
    )
  } else {
    let res = await getCity({
      parentCode: 0,
      level: 0,
    })
    options.value = res.data.map((item: any) => {
      return {
        value: item.areaCode,
        label: item.name,
        isLeaf: false,
      }
    })
  }
})
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.imgStyle {
  width: 100%;
  object-fit: contain;
}
</style>
